package com.util;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CopyObjectResult;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

public class OSSUtils {
	private static Logger logger = LoggerFactory.getLogger(OSSUtils.class);

	private final static String BUCKET_NAME = "zj-ddqc-video";
	private static String ACCESS_KEY_ID = "LTAIlOLLaPhbREKJ";
	private static String ACCESS_KEY_SECRET = "MYK6HHpg0qkNCq42oXbdaoutyCcNUu";
	private static String ENDPOINT = "oss-cn-hangzhou.aliyuncs.com";
//	private static OSS client;

//	public static final OSS createClient() {
//		if (null == client) {
//			client = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
//		}
//		return client;
//	}

	private static final ObjectMetadata getMetadata(String ossKey) {
		String filenameExtension = ossKey.substring(ossKey.lastIndexOf(".")).toLowerCase();
		ObjectMetadata metadata = new ObjectMetadata();
		metadata.setContentType(getcontentType(filenameExtension));
		return metadata;
	}

	/**
	 *
	 * @param ossKey      表示上传文件到OSS时需要指定包含文件后缀在内的完整路径
	 *                    ddqc/capture/20201113/0624bb78e17f476b98abd359c8f80ffc.jpg
	 * @param contentByte 上传Byte数组
	 */
	public static final boolean upload(String ossKey, byte[] contentByte) {
		OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
		try {
			ossClient.putObject(BUCKET_NAME, ossKey, new ByteArrayInputStream(contentByte), getMetadata(ossKey));
			logger.info("上传成功:{}", ossKey);
			return true;
		} catch (OSSException oe) {
			logger.error("Error Message: " + oe.getErrorMessage());
			logger.error("Error Code:    " + oe.getErrorCode());
			logger.error("Request ID:    " + oe.getRequestId());
			logger.error("Host ID:       " + oe.getHostId());
		} catch (ClientException ce) {
			logger.info("上传失败:{}", ce.getMessage());
		} finally {
			ossClient.shutdown();
		}
		return false;
	}

	/**
	 *
	 * @param ossKey 表示上传文件到OSS时需要指定包含文件后缀在内的完整路径
	 *               ddqc/capture/20201113/0624bb78e17f476b98abd359c8f80ffc.jpg
	 * @param file   上传文件
	 */
	public static final boolean upload(String ossKey, File file) {
		OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
		PutObjectRequest putObjectRequest = null;
		try {
			putObjectRequest = new PutObjectRequest(BUCKET_NAME, ossKey, file, getMetadata(ossKey));
			ossClient.putObject(putObjectRequest);
			logger.info("上传成功:{}", ossKey);
			return true;
		} catch (OSSException oe) {
			logger.error("Error Message: " + oe.getErrorMessage());
			logger.error("Error Code:    " + oe.getErrorCode());
			logger.error("Request ID:    " + oe.getRequestId());
			logger.error("Host ID:       " + oe.getHostId());
		} catch (ClientException ce) {ce.printStackTrace();
			logger.info("上传失败:{}", ce.getMessage());
		} finally {
			ossClient.shutdown();
		}
		return false;
	}

	/**
	 *
	 * @param ossKey      表示上传文件到OSS时需要指定包含文件后缀在内的完整路径
	 *                    ddqc/capture/20201113/0624bb78e17f476b98abd359c8f80ffc.jpg
	 * @param inputStream
	 */
	public static boolean upload(String ossKey, InputStream inputStream) {
		OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
		PutObjectRequest putObjectRequest = null;
		try {
			putObjectRequest = new PutObjectRequest(BUCKET_NAME, ossKey, inputStream, getMetadata(ossKey));
			ossClient.putObject(putObjectRequest);
			logger.info("上传成功:{}", ossKey);
			return true;
		} catch (OSSException oe) {
			logger.error("Error Message: " + oe.getErrorMessage());
			logger.error("Error Code:    " + oe.getErrorCode());
			logger.error("Request ID:    " + oe.getRequestId());
			logger.error("Host ID:       " + oe.getHostId());
		} catch (ClientException ce) {
			logger.info("上传失败:{}", ce.getMessage());
		} finally {
			ossClient.shutdown();
		}
		return false;
	}

	/**
	 * 复制文件
	 *
	 * @param sourceKey  源文件名称
	 *                   ddqc/capture/20201113/0624bb78e17f476b98abd359c8f80ffc.jpg
	 * @param destinationKey 目标文件名称
	 *                   ddqc/capture/20201113/0624bb78e17f476b98abd359c8f80ffd.jpg
	 *
	 */
	public static void copyFile(String sourceKey, String destinationKey) {
		OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
		CopyObjectResult result = null;
		try {
			result = ossClient.copyObject(BUCKET_NAME, sourceKey, BUCKET_NAME, destinationKey);
			logger.info("CopyObjectResult ETag:" + result.getETag() + " LastModified: " + result.getLastModified());
		} catch (OSSException oe) {
			logger.error("Error Message: " + oe.getErrorMessage());
			logger.error("Error Code:    " + oe.getErrorCode());
			logger.error("Request ID:    " + oe.getRequestId());
			logger.error("Host ID:       " + oe.getHostId());
		} catch (ClientException ce) {
			logger.info("复制失败:{}", ce.getMessage());
		} finally {
			ossClient.shutdown();
		}
	}

	/**
	 * 删除文件
	 *
	 * @param ossKey ddqc/capture/20201113/0624bb78e17f476b98abd359c8f80ffc.jpg
	 */
	public static void deleteFile(String ossKey) {
		OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
		try {
			ossClient.deleteObject(BUCKET_NAME, ossKey);
		} catch (OSSException oe) {
			logger.error("Error Message: " + oe.getErrorMessage());
			logger.error("Error Code:    " + oe.getErrorCode());
			logger.error("Request ID:    " + oe.getRequestId());
			logger.error("Host ID:       " + oe.getHostId());
		} catch (ClientException ce) {
			logger.info("删除失败:{}", ce.getMessage());
		} finally {
			ossClient.shutdown();
		}
	}

	/**
	 * 生成连接,默认1天
	 *
	 * @param ossKey ddqc/capture/20201113/0624bb78e17f476b98abd359c8f80ffc.jpg
	 * @return
	 */
	public static String getUrl(String ossKey) {
		return getUrl(ossKey, 1);
	}

	/**
	 * 生成连接
	 *
	 * @param ossKey
	 * @param day    过期天数
	 * @return
	 */
	public static String getUrl(String ossKey, long day) {
		OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
		try {
			long nowTime = System.currentTimeMillis();
			Date expiration = new Date(nowTime + Date2Utils.DAY * day);
			URL url = ossClient.generatePresignedUrl(BUCKET_NAME, ossKey, expiration);
			if (null != url) {
				return url.toString();
			}
		} catch (OSSException oe) {
			logger.error("Error Message: " + oe.getErrorMessage());
			logger.error("Error Code:    " + oe.getErrorCode());
			logger.error("Request ID:    " + oe.getRequestId());
			logger.error("Host ID:       " + oe.getHostId());
		} catch (ClientException ce) {
			logger.info("删除失败:{}", ce.getMessage());
		} finally {
			ossClient.shutdown();
		}
		return null;
	}

	private static final String getcontentType(String filenameExtension) {
		if (filenameExtension.equalsIgnoreCase(".bmp")) {
			return "image/bmp";
		}
		if (filenameExtension.equalsIgnoreCase(".gif")) {
			return "image/gif";
		}
		if (filenameExtension.equalsIgnoreCase(".jpeg") || filenameExtension.equalsIgnoreCase(".jpg")
				|| filenameExtension.equalsIgnoreCase(".png")) {
			return "image/jpg";
		}
		if (filenameExtension.equalsIgnoreCase(".html")) {
			return "text/html";
		}
		if (filenameExtension.equalsIgnoreCase(".txt")) {
			return "text/plain";
		}
		if (filenameExtension.equalsIgnoreCase(".vsd")) {
			return "application/vnd.visio";
		}
		if (filenameExtension.equalsIgnoreCase(".pptx") || filenameExtension.equalsIgnoreCase(".ppt")) {
			return "application/vnd.ms-powerpoint";
		}
		if (filenameExtension.equalsIgnoreCase(".docx") || filenameExtension.equalsIgnoreCase(".doc")) {
			return "application/msword";
		}
		if (filenameExtension.equalsIgnoreCase(".xml")) {
			return "text/xml";
		}
		return "image/jpeg";
	}

	/**
	 * 抓图路径
	 *
	 * @return
	 */
	public static final String getCapturePath() {
		String folderName = "capture";
		return getPath(folderName);
	}

	public static final String getMosaicPath() {
		String folderName = "mosaic";
		return getPath(folderName);
	}

	/**
	 * 客户营业执照
	 *
	 * @return
	 */
	public static final String getCustomerLicensePath() {
		String folderName = "customer/license";
		return getPath(folderName);
	}

	/**
	 * 用户身份证号码
	 *
	 * @return
	 */
	public static final String getUserIdCardPath() {
		String folderName = "user/idCard";
		return getPath(folderName);
	}

	/**
	 * 驾驶证/行驶证
	 *
	 * @return
	 */
	public static final String getDriverLicensePath() {
		String folderName = "driver/license";
		return getPath(folderName);
	}

	/**
	 * 华为Atlas500图片
	 *
	 * @return
	 */
	public static final String getHuaweiAtlas500Image() {
		String folderName = "huawei/atlas500/image";
		return getPath(folderName);
	}

	/**
	 * 华为Atlas500视频
	 *
	 * @return
	 */
	public static final String getHuaweiAtlas500Videostream() {
		String folderName = "huawei/atlas500/video";
		return getPath(folderName);
	}

	/**
	 * 文件夹名称
	 *
	 * @param folderName
	 * @return
	 */
	private static final String getPath(String folderName) {
		StringBuffer stringBuffer = new StringBuffer("ddqc");
		stringBuffer.append("/");
		stringBuffer.append(folderName);
		stringBuffer.append("/");
		stringBuffer.append(Date2Utils.getNowDateStr(Date2Utils.YYYYMMDD));
		stringBuffer.append("/");
		return stringBuffer.toString();
	}

	public static void main(String[] args) {

		/*下载图片到本地*/
		try {
			createFolder("d://ddqc//");
			downloadPicture(Arrays.asList("http://10.6.9.88:3000/web_api/v1/files/618444d7168048eeab4bb4c68299b828" +
					".jpeg"), "d://ddqc//", "汽车图片.jpg");
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 上传oss Demo
		File file = new File("d://ddqc//汽车图片.jpg");
		String fileId = UUID.randomUUID().toString().replace("-", "");
		String ossKey = OSSUtils.getCapturePath() + generateFilename(fileId, "jpg");
		System.out.println("ossKey:" + ossKey);
		try {
			upload(ossKey, file);
		} catch (Exception e) {
			e.printStackTrace();
		}
		String url = getUrl(ossKey);
		System.out.println(url);
		System.out.println(url.length());
		System.out.println(OSSUtils.getCapturePath());
		System.out.println(OSSUtils.getPath("capture"));

		// 上传完删除文件
		delAllFile("d:/ddqc");
	}

	public static String getUrl(String url,String imageName,String type) {
		String imageUrl = "";
		/*下载图片到本地*/
		try {
			createFolder("d://ddqc//");
			downloadPicture(Arrays.asList(url), "d://ddqc//", imageName);

			// 上传oss Demo
			File file = new File("d://ddqc//" + imageName);
			String fileId = UUID.randomUUID().toString().replace("-", "");
			String ossKey = OSSUtils.getCapturePath() + generateFilename(fileId, type);
			try {
				upload(ossKey, file);
			} catch (Exception e) {
				e.printStackTrace();
			}
			imageUrl = getUrl(ossKey);

			// 上传完删除文件
			delAllFile("d:/ddqc");
		} catch (Exception e) {
			e.printStackTrace();
		}


		return imageUrl;
	}

	public static String generateFilename(String fileId, String fileSuffix) {
		StringBuffer buffer = new StringBuffer();
		buffer.append(fileId).append(".").append(fileSuffix);
		return buffer.toString();
	}

	// 创建文件夹
	private static void createFolder(String folderPath) throws IOException {
		File file = new File(folderPath);
		file.mkdir();
	}

	// 删除文件夹 文件夹完整绝对路径
	private static void delFolder(String folderPath) {
		try {
			delAllFile(folderPath); // 删除完里面所有内容
			String filePath = folderPath;
			filePath = filePath.toString();
			File myFilePath = new File(filePath);
			myFilePath.delete(); // 删除空文件夹
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 删除指定文件夹下所有文件
// param path 文件夹完整绝对路径
	private static boolean delAllFile(String path) {
		boolean flag = false;
		File file = new File(path);
		if (!file.exists()) {
			return flag;
		}
		if (!file.isDirectory()) {
			return flag;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
				delFolder(path + "/" + tempList[i]);// 再删除空文件夹
				flag = true;
			}
		}
		return flag;
	}


	/**
	 * 传入要下载的图片的url列表，将url所对应的图片下载到本地
	 * @param urlList
	 * @throws Exception
	 */
	private static void downloadPicture(List<String> urlList, String path, String imgName) throws Exception {
		if(urlList==null||urlList.size()==0){
			return;
		}
		URL url = null;
		FileOutputStream fileOutputStream =null;
		InputStream inputStream =null;
		for (String urlString : urlList) {
			try {
				url = new URL(urlString);
				HttpURLConnection connection = (HttpURLConnection) url.openConnection();
				connection.addRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:55.0) Gecko/20100101 Firefox/55.0");
				connection.setConnectTimeout(10 * 1000);
				connection.setReadTimeout(15 * 1000);
				connection.setRequestProperty("Authorization", "Basic YWRtaW46ZWMxZTljZDkwOTk5MWIzOTNiMmU0Y2Y1NWM4MDVlMjY=");
				inputStream = connection.getInputStream();
				byte[] buffer = new byte[1024];
				int length;
				fileOutputStream= new FileOutputStream(path+ File.separator+ imgName);
				while ((length = inputStream.read(buffer)) != -1) {
					fileOutputStream.write(buffer, 0, length);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally{
				inputStream.close();
				fileOutputStream.flush();
				fileOutputStream.close();
			}
		}

	}


}
